package com.example.config;

import com.example.security.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    //当未登录或Token失效时，返回JSON格式的结果
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    //当用户没有访问权限时的处理器，用于返回JSON格式的处理结果
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    MyUserDetailsService myUserDetailsService;

    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    /**
     * 将自己设置的Jwt过滤器注入到Spring
     *
     * @return
     * @throws Exception
     */
    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter(authenticationManager());
        return filter;
    }

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    private final static String[] URL_WHITELIST = {
            "/login",//登录
            "/logout",//登出
            "/favicon.ico",//静态资源
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许跨域且由于使用的是JWT，我们这里不需要csrf
        http.cors().and().csrf().disable()
                //登录配置
                .formLogin()
                .usernameParameter("userName")
                .passwordParameter("password")
                .loginProcessingUrl("/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .and()
                //登出配置
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(jwtLogoutSuccessHandler)
                .and()
                //基于token，所以不需要session
                .sessionManagement()
//            .maximumSessions(1);
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //配置拦截规则
                .authorizeRequests()
                .antMatchers(SecurityConfig.URL_WHITELIST).permitAll() //无需登录即可访问
//            .antMatchers("/superAdmin/**").hasAnyRole("superAdmin") //需要登录，且角色为superAdmin才能访问
//            .antMatchers("/admin/**").hasAnyRole("admin","superAdmin") //需要登录，且角色为admin或者superAdmin才能访问
//            .antMatchers("/user/**").hasAnyRole("user","admin","superAdmin") //需要登录才能访问
                .anyRequest().authenticated()
                .and()
                //异常处理器
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .and()
                //配置自定义过滤器
                .addFilter(jwtAuthenticationFilter());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }
}